﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioController
{

    Dictionary<string, AudioSource> aduioSourceCache = new Dictionary<string, AudioSource>();
    Dictionary<string, AudioClip> audioClipCache = new Dictionary<string, AudioClip>();
    static AudioController instance_;
    static AudioController instance
    {
        get {
            if (instance_ == null)
            {
                instance_ = new AudioController();
            }
            return instance_;
        }
    }
    
    static void Play(string musicName,string musicLayer ,bool isLoop )
    {
        int setting = PlayerPrefs.GetInt(musicLayer);
       
        AudioSource audioSources;
        if (!instance.aduioSourceCache.TryGetValue(musicLayer, out audioSources))
        {
            GameObject o = new GameObject("audiosources_"+musicLayer);
            audioSources = o.AddComponent<AudioSource>();
            instance.aduioSourceCache[musicLayer] = audioSources;
            o.transform.SetParent(Camera.main.transform,false);
        }
        AudioClip clip;
        if (!instance.audioClipCache.TryGetValue(musicName, out clip))
        {
            clip = Resources.Load<AudioClip>("music/"+ musicName);
            instance.audioClipCache[musicName] = clip;
        }
        if (audioSources != null&& clip != null)
        {
            audioSources.clip = clip;
            audioSources.loop = isLoop;
            audioSources.Play();
            audioSources.mute = setting == 1;
        }

    }
    public static void PlaySound(string soundName,string musicLayer = "sound",bool isLoop = false)
    {
        
        Play(soundName, musicLayer, isLoop);
    }
    public static void PlayMusic(string soundName, string musicLayer = "music", bool isLoop = true)
    {
        Play(soundName, musicLayer, isLoop);
    }

    static void SetMusicState(bool state, string musicLayer = "music")
    {
        AudioSource asMusic;
        if (instance.aduioSourceCache.TryGetValue(musicLayer, out asMusic))
        {
            asMusic.mute = !state;
        }
    }

    public static void SetMusic(SoundSettingType sst,bool state)
    {
        string switchConfigName = sst== SoundSettingType.music?"music":"sound";
        PlayerPrefs.SetInt(switchConfigName, state?0:1);
        PlayerPrefs.Save();
        SetMusicState(state, switchConfigName);
    }

}

public enum SoundSettingType
{
    sound,
    music
}

